package cn.fancy.sdk.common.utils;

import android.util.Base64;
import android.util.Log;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

public class GuideEncodeAesRsaHelper {
    
    private GuideEncodeAesRsaHelper() {
    }
    
    private static class GetDataImplHolder {
        
        private static GuideEncodeAesRsaHelper instance = new GuideEncodeAesRsaHelper();
    }
    
    public static GuideEncodeAesRsaHelper getInstance() {
        return GetDataImplHolder.instance;
    }
    
    private final String plat_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt6jYwRq0kZK6DWrzkFFWAT7/3XxmMYE05nRorIAVmygAH0c7O14PqfT2bi0jeAc9dF8DbqdALqs7Ne3Eqh/QPsy+fyK6QVUb56dznabOy3SGOUXeZs/hQAE9i+QgNqumU40//9eNCwshVB3Jw0evjO3P7DGoMErHx67yZs+2PvVu9OSOloJbfc6+3S9rhO0aBY79FOJ9I74TgEODxBhR2MOEViz43cFTMhFKLc40psX3kd2+Bddd9GxKIGMG4eCemcbosb+8XX71Upb8wEy1z4hOUA62jnSLwdMNoy6Km7Ez2ZhB1Nfr8ix8Jo9hSGCfkiVIOgOYR2ujTyWLer3q9QIDAQAB";
    private PublicKey key;
    private Cipher cipher;
    
    public String encode(String value) {
        if(value == null){
            return null;
        }
        try {
            if (key == null) {
                X509EncodedKeySpec data = new X509EncodedKeySpec(Base64.decode(plat_public_key.getBytes(), Base64.NO_WRAP));
                KeyFactory factory = KeyFactory.getInstance("RSA");
                key = factory.generatePublic(data);
            }
            if (cipher == null) {
                cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
                cipher.init(Cipher.ENCRYPT_MODE, key);
            }
            byte[] encryptData = cipher.doFinal(value.getBytes());
            String base64EncryptData = Base64.encodeToString(encryptData, Base64.NO_WRAP);
            Log.i("rsaRegData", "rsaRegData success:" + value + ", encryptData:" + base64EncryptData);
    
            return base64EncryptData;
        } catch (Exception e) {
            Log.e("rsaRegData", "value:" + value + ", rsaRegData:" + e);
        }
        return "";
    }
}
